package a06_栈与队列;

import java.util.Deque;
import java.util.LinkedList;

/**
 * <p>
 * a03_用队列实现栈复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/1/13
 */
public class a03_用队列实现栈复习3 {
    public static void main(String[] args) {
//        Deque<Integer> deque = new LinkedList<>();
//        deque.add(1);
//        deque.add(2);
//        System.out.println(deque.poll());
        MyStack4 myStack4 = new MyStack4();
        myStack4.push(1);
        myStack4.push(2);
        System.out.println(myStack4.top());
        myStack4.push(3);
        System.out.println(myStack4.top());
//        System.out.println(myStack4.top());

//        System.out.println(myStack4.empty());
    }
}

class MyStack4 {

    private Deque<Integer> deque1;
    private Deque<Integer> deque2;

    //4
    //1,2,3
    public MyStack4() {
        deque1 = new LinkedList<>();
        deque2 = new LinkedList<>();
    }

    public void push(int x) {
        if(deque1.isEmpty() && deque2.isEmpty()){
            deque1.add(x);
        }else if(!deque1.isEmpty()){
            deque1.add(x);
        }else if(!deque2.isEmpty()){
            deque2.add(x);
        }
    }

    public int pop() {
        if (!deque1.isEmpty()){
            while (deque1.size() > 1) {
                deque2.add(deque1.poll());
            }
            return deque1.poll();
        }else {
            while (deque2.size() > 1) {
                deque1.add(deque2.poll());
            }
            return deque2.poll();
        }
    }

    public int top() {
        if (!deque1.isEmpty()){
            while (deque1.size() > 1) {
                deque2.add(deque1.poll());
            }
            Integer peek = deque1.peek();
            deque2.add(deque1.poll());
            return peek;
        }else {
            while (deque2.size() > 1) {
                deque1.add(deque2.poll());
            }
            Integer peek = deque2.peek();
            deque1.add(deque2.poll());
            return peek;
        }
    }

    public boolean empty() {
        return deque1.isEmpty() && deque2.isEmpty();
    }
}
